<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">商户回调</h1>
    </div>

    <!-- 搜索栏 -->
    <a-card class="mb-6">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="回调ID">
          <a-input v-model:value="searchForm.id" placeholder="请输入回调ID" />
        </a-form-item>
        <a-form-item label="订单号">
          <a-input v-model:value="searchForm.orderId" placeholder="请输入订单号" />
        </a-form-item>
        <a-form-item label="商户名称">
          <a-input v-model:value="searchForm.merchantName" placeholder="请输入商户名称" />
        </a-form-item>
        <a-form-item label="回调状态">
          <a-select v-model:value="searchForm.status" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="pending">待回调</a-select-option>
            <a-select-option value="success">回调成功</a-select-option>
            <a-select-option value="failed">回调失败</a-select-option>
            <a-select-option value="timeout">回调超时</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="订单类型">
          <a-select v-model:value="searchForm.orderType" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="payment">支付订单</a-select-option>
            <a-select-option value="refund">退款订单</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="回调类型">
          <a-select v-model:value="searchForm.callbackType" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="webhook">Webhook</a-select-option>
            <a-select-option value="http_post">HTTP POST</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon><search-outlined /></template>
            搜索
          </a-button>
          <a-button class="ml-2" @click="handleReset">
            <template #icon><reload-outlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 回调列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 1900 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderType'">
            <a-tag :color="orderTypeMap[record.orderType as keyof typeof orderTypeMap].color">
              {{ orderTypeMap[record.orderType as keyof typeof orderTypeMap].text }}
            </a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="statusMap[record.status as keyof typeof statusMap].color">
              {{ statusMap[record.status as keyof typeof statusMap].text }}
            </a-tag>
          </template>
          <template v-if="column.key === 'callbackType'">
            <a-tag :color="callbackTypeMap[record.callbackType as keyof typeof callbackTypeMap].color">
              {{ callbackTypeMap[record.callbackType as keyof typeof callbackTypeMap].text }}
            </a-tag>
          </template>
          <template v-if="column.key === 'retryInfo'">
            <span>{{ record.retryCount }}/{{ record.maxRetryCount }}</span>
          </template>
          <template v-if="column.key === 'responseCode'">
            <a-tag v-if="record.responseCode" :color="record.responseCode === 200 ? 'success' : 'error'">
              {{ record.responseCode }}
            </a-tag>
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'callbackUrl'">
            <a-tooltip :title="record.callbackUrl">
              <span class="truncate max-w-xs block">{{ record.callbackUrl }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical" />
              <a v-if="record.status === 'failed' && record.retryCount < record.maxRetryCount" @click="handleRetry(record)">重试</a>
              <a @click="handleViewDetails(record)">详情</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 商户回调详情弹窗 -->
    <a-modal v-model:open="showDetailModal" title="商户回调详情" width="1200px" :footer="null">
      <div v-if="currentCallback" class="space-y-6">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="回调ID">{{ currentCallback.id }}</a-descriptions-item>
          <a-descriptions-item label="订单号">{{ currentCallback.orderId }}</a-descriptions-item>
          <a-descriptions-item label="订单类型">
            <a-tag :color="orderTypeMap[currentCallback.orderType as keyof typeof orderTypeMap].color">
              {{ orderTypeMap[currentCallback.orderType as keyof typeof orderTypeMap].text }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="商户ID">{{ currentCallback.merchantId }}</a-descriptions-item>
          <a-descriptions-item label="商户名称">{{ currentCallback.merchantName }}</a-descriptions-item>
          <a-descriptions-item label="回调类型">
            <a-tag :color="callbackTypeMap[currentCallback.callbackType as keyof typeof callbackTypeMap].color">
              {{ callbackTypeMap[currentCallback.callbackType as keyof typeof callbackTypeMap].text }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="回调URL" :span="2">
            <a :href="currentCallback.callbackUrl" target="_blank">{{ currentCallback.callbackUrl }}</a>
          </a-descriptions-item>
          <a-descriptions-item label="回调状态">
            <a-tag :color="statusMap[currentCallback.status as keyof typeof statusMap].color">
              {{ statusMap[currentCallback.status as keyof typeof statusMap].text }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="重试次数">{{ currentCallback.retryCount }}/{{ currentCallback.maxRetryCount }}</a-descriptions-item>
          <a-descriptions-item label="响应状态码">
            <a-tag v-if="currentCallback.responseCode" :color="currentCallback.responseCode === 200 ? 'success' : 'error'">
              {{ currentCallback.responseCode }}
            </a-tag>
            <span v-else>-</span>
          </a-descriptions-item>
          <a-descriptions-item label="错误信息">{{ currentCallback.errorMessage || '无' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ currentCallback.createTime }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ currentCallback.updateTime }}</a-descriptions-item>
          <a-descriptions-item v-if="currentCallback.callbackTime" label="回调时间">{{ currentCallback.callbackTime }}</a-descriptions-item>
          <a-descriptions-item v-if="currentCallback.nextRetryTime" label="下次重试时间">{{ currentCallback.nextRetryTime }}</a-descriptions-item>
          <a-descriptions-item label="备注">{{ currentCallback.remark || '无' }}</a-descriptions-item>
        </a-descriptions>

        <a-divider>请求头</a-divider>
        <a-card size="small">
          <pre class="bg-gray-50 p-4 rounded text-sm overflow-auto">{{ currentCallback.requestHeaders }}</pre>
        </a-card>

        <a-divider>请求内容</a-divider>
        <a-card size="small">
          <pre class="bg-gray-50 p-4 rounded text-sm overflow-auto">{{ currentCallback.requestBody }}</pre>
        </a-card>

        <a-divider v-if="currentCallback.responseHeaders">响应头</a-divider>
        <a-card v-if="currentCallback.responseHeaders" size="small">
          <pre class="bg-gray-50 p-4 rounded text-sm overflow-auto">{{ currentCallback.responseHeaders }}</pre>
        </a-card>

        <a-divider v-if="currentCallback.responseBody">响应内容</a-divider>
        <a-card v-if="currentCallback.responseBody" size="small">
          <pre class="bg-gray-50 p-4 rounded text-sm overflow-auto">{{ currentCallback.responseBody }}</pre>
        </a-card>
      </div>
    </a-modal>

    <!-- 简单查看弹窗 -->
    <a-modal v-model:open="showViewModal" title="商户回调概览" width="600px" :footer="null">
      <div v-if="currentCallback">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="回调ID">{{ currentCallback.id }}</a-descriptions-item>
          <a-descriptions-item label="订单号">{{ currentCallback.orderId }}</a-descriptions-item>
          <a-descriptions-item label="商户名称">{{ currentCallback.merchantName }}</a-descriptions-item>
          <a-descriptions-item label="回调状态">
            <a-tag :color="statusMap[currentCallback.status as keyof typeof statusMap].color">
              {{ statusMap[currentCallback.status as keyof typeof statusMap].text }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="重试次数">{{ currentCallback.retryCount }}/{{ currentCallback.maxRetryCount }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ currentCallback.createTime }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import {
  mockData,
  updateMerchantCallback,
  statusMap,
  orderTypeMap,
  callbackTypeMap,
  type MerchantCallback
} from './data'
import {
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'

const searchForm = reactive({
  id: '',
  orderId: '',
  merchantName: '',
  status: '',
  orderType: '',
  callbackType: '',
})

const columns = [
  { title: '回调ID', dataIndex: 'id', key: 'id', width: 180 },
  { title: '订单号', dataIndex: 'orderId', key: 'orderId', width: 180 },
  { title: '订单类型', dataIndex: 'orderType', key: 'orderType', width: 100 },
  { title: '商户名称', dataIndex: 'merchantName', key: 'merchantName', width: 150 },
  { title: '回调状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '回调类型', dataIndex: 'callbackType', key: 'callbackType', width: 100 },
  { title: '回调URL', dataIndex: 'callbackUrl', key: 'callbackUrl', width: 200 },
  { title: '重试次数', dataIndex: 'retryInfo', key: 'retryInfo', width: 80 },
  { title: '响应码', dataIndex: 'responseCode', key: 'responseCode', width: 80 },
  { title: '回调时间', dataIndex: 'callbackTime', key: 'callbackTime', width: 150 },
  { title: '下次重试时间', dataIndex: 'nextRetryTime', key: 'nextRetryTime', width: 150 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' },
]

const loading = ref(false)
const tableData = ref<MerchantCallback[]>(mockData)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: mockData.length,
})

const showDetailModal = ref(false)
const showViewModal = ref(false)
const currentCallback = ref<MerchantCallback | null>(null)

const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    const filtered = mockData.filter(item => {
      const idMatch = !searchForm.id || item.id.includes(searchForm.id)
      const orderIdMatch = !searchForm.orderId || item.orderId.includes(searchForm.orderId)
      const merchantMatch = !searchForm.merchantName || item.merchantName.includes(searchForm.merchantName)
      const statusMatch = !searchForm.status || item.status === searchForm.status
      const orderTypeMatch = !searchForm.orderType || item.orderType === searchForm.orderType
      const callbackTypeMatch = !searchForm.callbackType || item.callbackType === searchForm.callbackType
      return idMatch && orderIdMatch && merchantMatch && statusMatch && orderTypeMatch && callbackTypeMatch
    })
    tableData.value = filtered
    pagination.total = filtered.length
    pagination.current = 1
    loading.value = false
  }, 500)
}

const handleReset = () => {
  searchForm.id = ''
  searchForm.orderId = ''
  searchForm.merchantName = ''
  searchForm.status = ''
  searchForm.orderType = ''
  searchForm.callbackType = ''
  tableData.value = mockData
  pagination.total = mockData.length
  pagination.current = 1
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

const handleView = (record: MerchantCallback) => {
  currentCallback.value = record
  showViewModal.value = true
}

const handleViewDetails = (record: MerchantCallback) => {
  currentCallback.value = record
  showDetailModal.value = true
}

const handleRetry = (record: MerchantCallback) => {
  updateMerchantCallback(record.id, {
    status: 'pending',
    retryCount: record.retryCount + 1,
    updateTime: new Date().toLocaleString(),
    nextRetryTime: undefined,
    errorMessage: undefined
  })
  message.success('商户回调已加入重试队列')
  handleSearch()
}
</script>

<style scoped>
.ant-table-wrapper {
  overflow-x: auto;
}

pre {
  max-height: 300px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>